const jwt = require("jsonwebtoken");
const config = require("../config");
const ResponseCode = require("../config/httpCode");
async function AuthGurad(ctx, next) {
  const { method, path } = ctx;
  if (
    path.startsWith("/views") ||
    path.startsWith("/public") ||
    path.startsWith("/uploads") ||
    path.startsWith("/static") ||
    path.startsWith("/shop") ||
    path.startsWith("/img") ||
    path.startsWith("/admin")
  ) {
    // 静态页面都可以访问
    await next();
  } else if (path.startsWith("/auth")) {
    // 登录注册相关也可以直接访问
    await next();
  } else if (path.startsWith("/api")) {
    // 部分展示需要白名单
    const token = ctx.header.token;
    if (token) {
      const user = jwt.verify(token, config.jwt_token);
      ctx.$$user = user;
      await next();
    } else {
      throw ResponseCode.NOT_AUTH;
    }
  }
}

module.exports = AuthGurad;
